<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>

<body>
  <h1>取消请求</h1>
  <input type="text" id="ipt">
  <button id="btn">提交</button>
  <button id="cancel">取消请求</button>

  <script>
    const myAxios = axios.create({
      baseURL: "/",
      timeout: 10000,
      headers: {}
    })


    const oIpt = document.getElementById('ipt')
    const oBtn = document.getElementById('btn');
    const oCancel = document.getElementById('cancel');

    // //拿到一个取消请求的对象(是一个构造函数)
    // const CancelToken = axios.CancelToken;
    // let cancel = null;

    // oBtn.onclick = async function () {
    //   const iptValue = oIpt.value;
    //   try {
    //     const result = await myAxios.get("/userLazy", {
    //       params: {
    //         userId: iptValue,
    //       },
    //       // 在配置对象中配置一个cancelToken的配置项,值是实例化的CancelToken对象
    //       cancelToken: new CancelToken((c) => {
    //         //当请求发送的时候,这个回调函数会被执行,并接受一个参数,这个参数其实就是取消当前请求的函数
    //         console.log(c);
    //         cancel = c;
    //         //一旦请求被中断,则会交给catch处理这个异常
    //       })
    //     })
    //     console.log(result.data);
    //   } catch (e) {
    //     console.log(e.message, "出现错误");
    //   }
    // }

    // //取消请求点击事件
    // oCancel.onclick = function () {
    //   cancel()
    // }


    const CancelToken = axios.CancelToken;
    let cancel = null

    btn.onclick = async function () {
      const iptValue = oIpt.value;
      try {
        const result = await myAxios.get("userLazy", {
          params: {
            userId: "001"
          },
          cancelToken: new CancelToken((c) =>{
            // executor 函数接收一个 cancel 函数作为参数
            cancel = c;
          })
        })
        console.log(result.data);
      } catch (e) {
        console.log(e.message);
      }
    }

    oCancel.onclick = function () {
      cancel()
    }
  </script>
</body>

</html>